﻿using System;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;
using WorldMapBase;
using WorldMapBase.Tile.Pool;
using WorldMapNew;
using XLua;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using DG.Tweening;
using System.Timers;
using Yoozoo.Mars.Got;
using LogSystem;

/// <summary>
/// 地图迷雾
/// </summary>
public class WorldMapFog
{
    private ResLoader m_resLoader;
    public int mapFogAllSize = 1800;
    public int mapFogOutSize = 20; // (2000 - 1800) / 10
    private Texture2D fogMask;
    private GameObject fogObj;
    private Material fogMat;
    private Material fogShadowMat;

    private bool fogDataInit = false;
    private Dictionary<int, bool> fogUnlockIds = new Dictionary<int, bool>();

    private int unlockingFogId = 0;
    private bool isLocking = false;
    private float _StateValue = 0;
    private int hightFogId = -1;
    private bool bFogShow = false;
    private int fogLineNum = 0;
    private int fogMaskLineNum = 0;// 采样图尺寸

    private  Dictionary<int,int> fogUpdateRecord = new Dictionary<int, int>();
    private Dictionary<int, bool> fogExploreIds = new Dictionary<int, bool>(); // 正在探索的迷雾id <id,bShow> bShow才显示高亮
    public void InitFog(LuaFunction callBack)
    {
        //WorldMapFogData fogData = WorldMapConfigData.GetFogData();
        //// 实例化迷雾采样图
        //fogLineNum = fogData.mapWidth / fogData.fogSize;
        //fogMaskLineNum = fogData.mapWidth / fogData.fogSize + mapFogOutSize;
        //fogMask = new Texture2D(fogMaskLineNum, fogMaskLineNum, TextureFormat.RGBA32, true, false);
        //fogMask.filterMode = FilterMode.Bilinear;
        ////
        //for (int x = 0; x < fogMaskLineNum; x++)
        //{
        //    for (int y = 0; y < fogMaskLineNum; y++)
        //    {
        //        fogMask.SetPixel(x, y, Color.white);
        //    }
        //}
        //// 实例化迷雾obj
        //string mapFogPrefabMapPath = "Assets/ResourcesAssets/World/prefabs/sandtable/fog/fog.prefab";
        //if (m_resLoader == null)
        //{
        //    m_resLoader = ResLoader.Alloc();
        //}
        //m_resLoader.Add2Load(mapFogPrefabMapPath, (bool success, string assetName, object asset) =>
        //{
        //    if (success)
        //    {
        //        // 捕获对应节点
        //        fogObj = GameObject.Instantiate<GameObject>(asset as GameObject);
        //        fogObj.name = "MapFog";
        //        fogMat = fogObj.GetComponent<MeshRenderer>().material;
        //        fogShadowMat = fogObj.transform.GetChild(0).GetComponent<MeshRenderer>().material;
        //        // 设置采样图
        //        fogMat.SetTexture("_StateInfoTex", fogMask);
        //        fogShadowMat.SetTexture("_StateInfoTex", fogMask);
        //        fogObj.SetActive(bFogShow);
        //        if (callBack != null)
        //        {
        //            callBack.Call();
        //        }
        //        // 更新迷雾解锁
        //        UnlockAllFog();
        //    }
        //});
        //m_resLoader.Load();

    }

    public void Destroy()
    {
        if (m_resLoader != null)
        {
            m_resLoader.Recycle2Cache();
            m_resLoader = null;
        }
        //if (fogObj)
        //{
        //    GameObject.Destroy(fogObj);
        //    fogObj = null;
        //    GameObject.Destroy(fogMask);
        //    fogMask = null;
        //}
        //fogMat = null;
        //fogShadowMat = null;
        //fogDataInit = false;
        //fogUnlockIds.Clear();
        //fogExploreIds.Clear();

    }

    public void UpdateFogShow(bool bShow)
    {
        bFogShow = bShow;
        if (fogObj != null)
        {
            fogObj.SetActive(bFogShow);
        }
    }

    public void ShowHightLightFog(int fog_x, int fog_y)
    {
        //int hightFogIdx1 = fog_x + fog_y * fogLineNum;
        //int fodId = WorldMapConfigData.GetFogIdByIndex(hightFogIdx1);
        //if (fodId != hightFogId)
        //{
        //    int oldHightFogId = hightFogId;
        //    hightFogId = fodId;
        //    UpdateFogShow(oldHightFogId);
        //    UpdateFogShow(hightFogId);
        //}
    }

    public void ShowExploreHightLightFog(int fogId, bool bShow)
    {
        //fogExploreIds[fogId] = bShow;
        //UpdateFogShow(fogId);
    }

    public void HideHightLightFog()
    {
        //int oldHightFogId = hightFogId;
        //hightFogId = -1;
        //UpdateFogShow(oldHightFogId);
    }

    public void UpdateFogShow(int fogId)
    {
        //if (fogId < 0 || fogMask == null) return;
        //List<Vector2Int> tiles = WorldMapConfigData.GetFogTilesById(fogId);
        //if (tiles != null)
        //{
        //    int halfOut = mapFogOutSize / 2;
        //    for (int i = 0; i < tiles.Count; i++)
        //    {
        //        Vector2Int tile = tiles[i];
        //        Color c = GetColorByState(tile);
        //        fogMask.SetPixel(tile.x + halfOut, tile.y + halfOut, c);
        //    }
        //    fogMask.Apply();
        //}
    }

    public void UpdateFogByPos(int fog_x,int fog_y,int size, bool bShow)
    {
        //WorldMapFogData fogData = WorldMapConfigData.GetFogData();
        //int lineNum = (fogData.mapWidth / fogData.fogSize);
        //int halfOut = mapFogOutSize / 2;
        //// 更新(fog_x,fog_y)周围size范围的迷雾消散
        //for (int x = fog_x - size; x <= fog_x + size; x++)
        //{
        //    for (int y = fog_y - size; y <= fog_y + size; y++)
        //    {
        //        int fogIdx = x + y * lineNum;
        //        int unlockNum = 0;
        //        if (fogUpdateRecord.ContainsKey(fogIdx))
        //        {
        //            unlockNum = fogUpdateRecord[fogIdx];
        //        }
        //        if (bShow)
        //        {
        //            unlockNum++;
        //        }
        //        else
        //        {
        //            unlockNum--;
        //            unlockNum = unlockNum < 0 ? 0 : unlockNum;
        //        }
        //        fogUpdateRecord[fogIdx] = unlockNum;
        //        Color c = GetColorByState(new Vector2Int(x, y));
        //        fogMask.SetPixel(x + halfOut,y + halfOut,c);
        //    }
        //}
        //fogMask.Apply();
    }
    
    public void UnlockFog(int id)
    {
        //if (isLocking)
        //{
        //    UnlockFogEnd();
        //}
        //isLocking = true;
        //unlockingFogId = id;
        //// 设置目标mask
        //UpdateFogShow(id);
        //// 定时修改
        //Timers.inst.Add(0.01f, 100, (id) =>
        //{
        //    _StateValue += 0.01f;
        //    if (fogMat && fogShadowMat)
        //    {
        //        fogMat.SetFloat("_StateValue", _StateValue);
        //        fogShadowMat.SetFloat("_StateValue", _StateValue);
        //        if (_StateValue >= 1)
        //        {
        //            // 结束修改mask
        //            UnlockFogEnd();
        //        }
        //    }
        //});
    }

    void UnlockFogEnd()
    {
        if(fogMat == null || fogShadowMat == null) return; //可能还没接错
        isLocking = false;
        int fogId = unlockingFogId;
        fogUnlockIds[fogId] = true;
        unlockingFogId = 0;
        _StateValue = 0;
        UpdateFogShow(fogId);
        fogMat.SetFloat("_StateValue", 0);
        fogShadowMat.SetFloat("_StateValue", 0);
    }

    public void UnlockAllFog()
    {
        //if (!fogDataInit) return;// 数据未初始化
        //if (fogObj == null) return;// 迷雾实例未初始化
        //int halfOut = mapFogOutSize / 2;
        //foreach (int id in fogUnlockIds.Keys)
        //{
        //    if (fogUnlockIds[id])
        //    {
        //        List<Vector2Int> tiles = WorldMapConfigData.GetFogTilesById(id);
        //        if (tiles != null)
        //        {
        //            for (int ii = 0; ii < tiles.Count; ii++)
        //            {
        //                Vector2Int tile = tiles[ii];
        //                Color c = GetColorByState(tile);
        //                fogMask.SetPixel(tile.x + halfOut, tile.y + halfOut, c);
        //            }
        //        }
        //    }
        //}

        //fogMask.Apply();
    }

    public void SetUnlockFogId(string id_str)
    {
        //fogDataInit = true;
        //if (!string.IsNullOrEmpty(id_str))
        //{
        //    string[] ids = id_str.Split("|");
        //    for (int i = 0; i < ids.Length; i++)
        //    {
        //        string id = ids[i];
        //        int.TryParse(id, out int int_id);
        //        fogUnlockIds[int_id] = true;
        //    }
        //}
        //UnlockAllFog();
    }

    Color GetColorByState(Vector2Int vec)
    {
        WorldMapFogData fogData = WorldMapConfigData.GetFogData();
        int lineNum = (fogData.mapWidth / fogData.fogSize);
        int fogIdx = vec.x + vec.y * lineNum;
        int fodId = WorldMapConfigData.GetFogIdByIndex(fogIdx);
        Color c = Color.white;
      
        // 查询正在解锁状态
        if (unlockingFogId == fodId)
        {
            c.g = 0;
        }
        // 查询解锁状态
        if (fogUnlockIds.ContainsKey(fodId) || (fogUpdateRecord.ContainsKey(fogIdx) && fogUpdateRecord[fogIdx] > 0))
        {
            c.g = 0;
            c.r = 0;
        }
        // 查询高亮状态
        if (hightFogId == fodId)
        {
            c.b = 0;
        }
        // 正在探索高亮
        if (fogExploreIds.ContainsKey(fodId) && fogExploreIds[fodId])
        {
            c.b = 0;
        }
        return c;
    }
}